package printRecord

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"hosptial-record/api/base"
	"hosptial-record/forms"
	"hosptial-record/global"
	"hosptial-record/global/response"
	"hosptial-record/model"
	"net/http"
)

// List 记录列表
func List(ctx *gin.Context) {
	var form forms.GetPrintRecordList
	if err := ctx.ShouldBind(&form); err != nil {
		base.HandleValidatorError(ctx, err)
		return
	}
	fmt.Println(form.PatientName)
	db := global.DB
	if form.Type != nil {
		db = db.Where("type = ?", &form.Type)
	}
	if form.PatientName != "" {
		db = db.Where("patient_name = ?", form.PatientName)
	}
	if form.StartTime != nil {
		db = db.Where("add_time >= ?", &form.StartTime)
	}
	if form.EndTime != nil {
		db = db.Where("add_time <= ?", &form.EndTime)
	}
	var total int64
	var list []model.PrintRecord
	res := db.
		Debug().
		Model(&model.PrintRecord{}).
		Count(&total).
		Order("id desc").
		Scopes(base.Paginate(int(form.Page), int(form.PageSize))).
		Find(&list)
	if res.Error != nil {
		zap.S().Errorw("PrintRecord [List] 失败:", "msg", zap.Error(res.Error))
		ctx.JSON(http.StatusBadGateway, response.BaseResponse{
			Msg:  "获取失败",
			Data: res.Error,
		})
	}
	ctx.JSON(http.StatusOK, response.ListResponse{
		Msg: "获取成功",
		Data: response.ListData{
			Data:  list,
			Total: total,
		},
	})
}

// Create 创建记录
func Create(ctx *gin.Context) {
	var form forms.PrintRecordForm
	if err := ctx.ShouldBind(&form); err != nil {
		base.HandleValidatorError(ctx, err)
		return
	}
	record := model.PrintRecord{
		PatientName:    form.PatientName,
		PatientNumber:  form.PatientNumber,
		UseUser:        form.UseUser,
		Desc:           form.Desc,
		Type:           form.Type,
		OperateAccount: form.OperateAccount,
	}
	res := global.DB.Create(&record)
	if res.Error != nil {
		zap.S().Errorw("PrintRecord [Create] 失败:", "msg", zap.Error(res.Error))
		ctx.JSON(http.StatusBadGateway, response.BaseResponse{
			Msg:  "创建失败",
			Data: res.Error,
		})
		return
	}
	ctx.JSON(http.StatusOK, response.BaseResponse{
		Msg: "创建成功",
	})
}

// Delete 删除记录
func Delete(ctx *gin.Context) {
	id, err := base.GetID2Param(ctx)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, response.BaseResponse{
			Msg: "ID不合法",
		})
		return
	}
	res := global.DB.Unscoped().Delete(&model.PrintRecord{}, id)
	if res.Error != nil {
		zap.S().Errorw("PrintRecord [Delete] 失败:", "msg", zap.Error(res.Error))
		ctx.JSON(http.StatusBadGateway, response.BaseResponse{
			Msg:  "删除失败",
			Data: res.Error,
		})
		return
	}
	if res.RowsAffected == 0 {
		ctx.JSON(http.StatusBadRequest, response.BaseResponse{
			Msg: "删除的记录不存在",
		})
		return
	}
	ctx.JSON(http.StatusOK, response.BaseResponse{
		Msg: "删除成功",
	})
}
